# -*- coding: utf-8 -*-

#relatorio do professor

from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
from django import forms
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404, redirect
from django.core.mail import send_mail, BadHeaderError
from django.contrib.auth.forms import *
from django.db.models.query_utils import Q
from si_4k.sistema.models import *
from si_4k.sistema.forms import *
from django.contrib.auth.forms import *
from datetime import datetime
from django.contrib.auth.forms import PasswordChangeForm
from PIL import *
from django.contrib.auth.decorators import permission_required
from si_4k.py_docx.docx import *
from django.core.servers.basehttp import FileWrapper
from decimal import *
import os



def tabela_relatorio_professor(request):
    lista_professores = Professor.objects.all()
    return render_to_response('tabela_relatorio_professor.html', locals(), context_instance=RequestContext(request))
    
def tabela_aula(request, id_professor):
	prof = Professor.objects.get(id = id_professor)
	data_inicio = request.POST['data_inicio'+id_professor]
	data_inicio = data_inicio.split('-')
	data_inicio = data_inicio[2] + '-' + data_inicio[1] +'-'+ data_inicio[0]
	data_final = request.POST['data_fim'+id_professor]
	data_final = data_final.split('-')
	data_final = data_final[2] + '-' + data_final[1] + '-' + data_final[0]
	lista_aulas = Aula.objects.filter(professor = prof).filter(inicio__gte = data_inicio).filter(fim__lte = data_final)
	valor_total = 0
	for aula in lista_aulas:
		delta = aula.fim - aula.inicio
		delta = Decimal(delta.seconds)/3600
		valor_aula = delta*Decimal(aula.professor.valor)
		valor_total = valor_total + valor_aula
	return render_to_response('tabela_aula.html', locals(), context_instance=RequestContext(request))
	

def relatorio_professor(request, id_professor,data_inicio,data_final):
    #prefixo = ''

	prefixo = '/home/edu4k/webapps/static_media/relatorios/'
	desconto = request.POST['desconto']
	# Default set of relationshipships - these are the minimum components of a document
	relationships = relationshiplist()
	
	# Make a new document tree - this is the main part of a Word document
	document = newdocument()
	
	# This xpath location is where most interesting content lives 
	docbody = document.xpath('/w:document/w:body', namespaces=nsprefixes)[0]
	
	# Append two headings and a paragraph
	
	
	professor = Professor.objects.get(id = id_professor)
	professor_nome = professor.detalheusuario.nome
	professor_valor = professor.valor
	
	lista = ['Dia', 'Aluno', 'Local', 'Hora', 'Minuto', 'Valor da Aula', 'Valor Total']
	
	data_hoje = datetime.now()
	
	
	lista2 = [lista]
	
	lista_aulas = Aula.objects.filter(professor = professor).filter(inicio__gte=data_inicio).filter(inicio__lt=data_final).filter(valido=True)
	valor_soma = 0
	for aula in lista_aulas:
		
		lista_alunos = aula.aluno.all()
		lista_nome = ''
		for aluno in lista_alunos:
			lista_nome = lista_nome+aluno.nome+';'
		
		delta = aula.fim - aula.inicio
		delta1 = Decimal(delta.seconds)/3600
		valor_total = delta1*Decimal(aula.professor.valor)
		valor_soma = valor_soma + valor_total
		
		
	
		
		s = delta.seconds
		hours  = s / 3600
		s = s - (hours*3600)
		minutes = s/60
		seconds = s - (minutes*60)
		
	
		
		
		
		lista2.append([str(aula.inicio.day), lista_nome, str(aula.local), str(hours) + 'h', str(minutes) + 'min', 'R$'+ str(professor_valor), 'R$' + str(valor_total)])
		
	meses = {1:'Janeiro', 2:'Fevereiro', 3:'Marco' , 4:'Abril', 5:'Maio', 6:'Junho', 7:'Julho', 8:'Agosto', 9:'Setembro', 10:'Outubro', 11:'Novembro', 12:'Dezembro'}
		
	data = datetime.now()
	data1 = data.day
	data2 = data.month
	data3 = data.year
	mes = meses[data.month]
	valor_desconto = valor_soma - Decimal(desconto)
	
	
	docbody.append(heading('''Recibo''',1))
	docbody.append(paragraph(''))
	
	docbody.append(paragraph('Eu,  ' +str(professor_nome) + ', portador (a) do R.G.:_________________________, me declaro ciente que recebi da 4K Assessoria Educacional e Treinamentos, localizada a Rua Bernardino de Campos, 325 - Brooklin, CEP: 04620-001, a quantia de R$ '+ str(valor_desconto) +', referentes a servicos prestados abaixo:'))
	   
	docbody.append(paragraph(''))
	
	docbody.append(table(lista2))
	
	docbody.append(paragraph(''))
	
	docbody.append(paragraph('Valor total: R$' + str(valor_soma)))
	docbody.append(paragraph('Desconto: R$' + str(desconto)))
	docbody.append(paragraph('Valor total com desconto: R$' + str(valor_desconto)))
	docbody.append(paragraph(''))  
	docbody.append(paragraph('Para maior clareza firmo o presente.'))
	docbody.append(paragraph(''))
	docbody.append(paragraph('Sao Paulo, ____ de ' + str(mes)  + ' de ' +str(data3) + '.'))
	docbody.append(paragraph('__________________________'))
	docbody.append(paragraph('ASSINATURA'))
	
	# Create our properties, contenttypes, and other support files
	coreprops = coreproperties(title='Python docx demo',subject='A practical example of making docx from Python',creator='Mike MacCana',keywords=['python','Office Open XML','Word'])
	appprops = appproperties()
	global professor_contenttypes
	global professor_websettings
	global professor_wordrelationships
	professor_contenttypes = contenttypes()
	professor_websettings = websettings()
	professor_wordrelationships = wordrelationships(relationships)
	
	# Save our document
	savedocx(document,coreprops,appprops,professor_contenttypes,professor_websettings,professor_wordrelationships,prefixo+'relatorio_professor.docx')
	
	professor.ultimo_recibo = data.strftime("%d/%m/%y")
	professor.save()
	
	myfile = open(prefixo+'relatorio_professor.docx', 'rb+')
	
	response = HttpResponse(FileWrapper(myfile), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
	response['Content-Disposition'] = 'attachment; filename=relatorio_professor.docx'
	
	return response